package com.itheima.health.jersey;

import com.itheima.resources.UploadUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller  //  注意： 页面跳转  不要使用@RestController
@RequestMapping("jersey")
public class JerseyController {

    @RequestMapping("/upload.do")
    public String upload(@RequestParam("upload") MultipartFile file) {
        //  文件上传到 9001 服务器
        if (!file.isEmpty()) {
            try {
                String originalFilename = file.getOriginalFilename();// xxxxx.jpg
                String filename = UploadUtils.generateRandonFileName(originalFilename);
                //  上传到 9001  tomcat服务器上
                Client client = new Client(); // 创建上传文件客户端对象
                //  连接文件服务器地址，通过put方法 进行文件上传
                WebResource resource = client.resource("http://127.0.0.1:9001/uploads/" + filename);
                resource.put(file.getBytes());
                return "redirect:/upload/success.html";
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return "static/upload/success.html";
    }
}
